/*globals YUI database */
/*jslint white: true, browser: true, onevar: false, undef: true, nomen: false, eqeqeq: true, plusplus: true, bitwise: true, regexp: false, newcap: true, immed: true, strict: false */

/**
 *
 */
YUI.add('v3-dialog', function (Y) {
    var YL = Y.Lang,
        Node = Y.Node;

    var defaultOptions = {
            'centered': false,
            'constrain2view': false,
            'draggable': false,
            'resizable': false,
            'destroyOnClose': true
        };

    var dialogMarkup = [
            '<div class="yui3-dialog-loading">',
            '<div class="yui3-widget-hd"></div>',
            '<div class="yui3-widget-bd"></div>',
            '<div class="yui3-widget-ft"></div>',
            '</div>'
        ].join('');

    var headerContentMarkup = '<div>{title}{closeButton}</div>';
    var headerCloseButtonMarkup = '<button type="button" class="yui3-dialog-close-button"></button>';
    var headerTitleMarkup = '<span class="yui3-dialog-caption">{title}</span>';

    var seedId = 0;

    var getXY = function () {
        return [seedId * 60, seedId * 40];
    };

    function Dialog() {
        seedId += 1;
        var config = arguments.length > 0 ? arguments[0] : {};

        config.id = YL.isValue(config.id) ? config.id : 'dialog-' + seedId;
        if (!config.srcNode) {
            config.srcNode = Node.create(dialogMarkup);
        }

        if (!config.headerContent) {
            var hcReplaceObject = {};
            hcReplaceObject.title = config.title ? Y.substitute(headerTitleMarkup, {'title': config.title}) : '';
            hcReplaceObject.closeButton = config.close ? headerCloseButtonMarkup : '';

            if (hcReplaceObject.title || hcReplaceObject.closeButton) {
                config.headerContent = Y.substitute(headerContentMarkup, hcReplaceObject);
            }
        }

        Y.mix(config, defaultOptions);

        if (!config.xy && !config.centered) {
            config.xy = getXY(seedId);
        }

        if (!config.zIndex) {
            config.zIndex = seedId;
        }

        Dialog.superclass.constructor.apply(this, [config]);

        if (config.draggable) {
            this.plug(Y.Plugin.Drag);
        }
        Y.delegate('click', this.onClose, config.srcNode, 'button.yui3-dialog-close-button', this, config);
    }

    Y.mix(Dialog, {
        'NS': 'dialog',
        'NAME': 'dialog'
    });

    Y.extend(Dialog, Y.Overlay, {
        // Prototype properties
        getNode: function () {
            return Y.one('#' + this.get('id'));
        },

        onClose: function (event) {
            this.unplug();
            this.destroy();
        }
    }, {
        // Static properties
    });

    Y.V3_Dialog = Dialog;
}, '0.1', {
    'requires': ['overlay', 'substitute']
});
